package pub.tbc.api.util;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * @author tbc on 2017/3/16 09:19:49.
 */
@Slf4j
public class NettyHttpUtil {
    private static EventLoopGroup clientGroup = new NioEventLoopGroup();
    private static Bootstrap bootstrap = new Bootstrap();

    static {
        bootstrap.channel(NioSocketChannel.class)
                .group(clientGroup)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, false);
    }

    public static EventLoopGroup getClientEventLoopGroup() {
        return clientGroup;
    }

    public static Bootstrap getDefaultBootstrap() {
        return bootstrap;
    }

    public static void closeOnFlush(Channel ch) {
        if (ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

    public static String requestToString(FullHttpRequest request) {
        return "Host: " + request.headers().get("Host") + ", uri: " + request.uri();
    }

    public static void main(String[] args) {
        EventLoopGroup clientGroup = getClientEventLoopGroup();
    }
}
